package com.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.neomanager.login.model.AdminInfo;

public class LoginCheckInterceptor extends HandlerInterceptorAdapter 
{
	public Logger logger = Logger.getLogger(this.getClass());

	/*
	 * preHandle - Controller 실행 요청전 postHandle - view(jsp)로 forward되기 전에
	 * afterCompletion - 끝난뒤
	 * 
	 * login 검사를 해야 될 시점은 Dispatcher가 해당 controller로 이어주기 전에 해야 되므로
	 * preHandle메소드를 사용
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception 
	{
		String url = request.getRequestURI();

		// 로그인 시 에는 통과하도록
		if (url.substring(0,6).equals("/login"))
			return true;

		// 세션 검사
		HttpSession session = request.getSession();
		AdminInfo adminInfo = (AdminInfo) session.getAttribute("adminInfo");

		if (adminInfo == null) 
		{
			response.sendRedirect("/login/login.do");
			return false;
		}
		else if (adminInfo.getAdmin_id() == null || adminInfo.getAdmin_id().equals("")) 
		{
			response.sendRedirect("/login/login.do");
			return false;
		}
		
		return true;
	}
	
}
